import { RouteRecordRaw } from 'vue-router'

const layouts = import.meta.globEager('@/layouts/*.vue')
const views = import.meta.globEager(`@/views/*/*.vue`)
function getLayoutsRoutes() {
	const layoutRoutes: RouteRecordRaw[] = []
	Object.entries(layouts).forEach(([filePath, module]) => {
		const fileName = filePath.replace(/.+layouts\/|\.vue/gi, '')
		const route = configRoute(fileName, module)
		route.children = getChildrenRoutes(fileName)
		layoutRoutes.push(route)
	})
	return layoutRoutes
}

/*下面这两个函数就是为上面那个函数服务的*/
function getChildrenRoutes(dirName: string) {
	const childrenRoutes: RouteRecordRaw[] = []
	Object.entries(views).forEach(([filePath, module]) => {
		if (filePath.includes(dirName)) {
			const fileName = filePath.replace(/.+views\/|\.vue/gi, '')
			childrenRoutes.push(configRoute(fileName, module))
		}
	})
	return childrenRoutes
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function configRoute(fileName: string, module: { [key: string]: any }) {
	const route: RouteRecordRaw = {
		path: `/${fileName}`,
		name: fileName,
		component: module.default,
	}
	return Object.assign(route, module.default?.route) //如果模块有route对象，则将其里面的属性添加到（或覆盖掉）这里的route中
}
const routes = import.meta.env.VITE_IS_AUTOLOAD === 'true' ? getLayoutsRoutes() : [] //根据环境变量判断是否自动加载路由
export default routes
